package com.leyou.item.web;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.vo.PageResult;
import com.leyou.common.vo.ResponseResult;
import com.leyou.item.pojo.Category;
import com.leyou.item.service.CategoryService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    @GetMapping("/page")
    public ResponseEntity<ResponseResult<PageResult<Category>>> queryCategoryListWithPage(
            @RequestParam(value = "currentPage", defaultValue = "1") Integer currentPage,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize
    ) {
        PageResult<Category> result = categoryService.queryCategoryListWithPage(currentPage, pageSize);

        return ResponseEntity.ok(ResponseResult.success(result));
    }

    @GetMapping("/level")
    public ResponseEntity< ResponseResult<List<Category>>> queryCategoryWithLevel(@RequestParam(value = "level", defaultValue = "3") Integer level) {
        Category category = new Category();
        category.setId(0);
        categoryService.queryWithLevel(category, level);
        List<Category> categories = category.getChildren();
        if (CollectionUtils.isEmpty(categories)) {
            throw new LyException(ExceptionEnum.Category_NOT_FOUND);
        }
        return ResponseEntity.ok(ResponseResult.success(categories));
    }

    @GetMapping("/allLevel")
    public ResponseEntity< ResponseResult<List<Category>>> queryCategoryWithAllLevel() {
        Category category = new Category();
        category.setId(0);
        categoryService.queryWithAllLevel(category);
        List<Category> categories = category.getChildren();
        if (CollectionUtils.isEmpty(categories)) {
            throw new LyException(ExceptionEnum.Category_NOT_FOUND);
        }
        return ResponseEntity.ok(ResponseResult.success(categories));
    }

    @PostMapping
    public ResponseEntity<ResponseResult<Object>> addCategory(@RequestBody Category category) {
       categoryService.addCategory(category);
        return ResponseEntity.ok(ResponseResult.success(null));
    }

    @PutMapping
    public ResponseEntity<ResponseResult<Object>> updateCategory(@RequestBody Category category) {
        categoryService.updateCategory(category);
        return ResponseEntity.ok(ResponseResult.success(null));
    }

    @DeleteMapping
    public ResponseEntity<ResponseResult<Object>> deleteCategory(@RequestParam(name = "id") int id, @RequestParam(name = "level") int level) {
        categoryService.deleteCategory(id, level);

        return ResponseEntity.ok(ResponseResult.success(null));
    }
}
